'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  Navigator,
  Image,
  BackAndroid,
  ListView,
  TouchableOpacity,
  TouchableWithoutFeedback,
  Dimensions,
  DeviceEventEmitter,
  ProgressBarAndroid

} from 'react-native';

import RNFileSearch from './RNFileSearch';
import DownloadControl from './DownloadControl';
var width = Dimensions.get('window').width;

class ListComponent extends Component{
  constructor(props){
    super(props);
    Array.prototype.remove = function(val) {
      var index = this.indexOf(val);
      if (index > -1) {
          this.splice(index, 1);
      }
   }
    this.state = {
      dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
      allSelect: false,
      titleRight:'全选',
      unuploaded: true,
      checkRows: [], //被选择的文件
      onCloudNum: 0,
      onNativeNum: 0,
      nativeDatas: [], //本地数据
      cloudDatas: [], //分类型文件云端数据 MP3，MP4，txt
      allCloudDatas: this.props.data, //云端上的全部数据
      type: this.props.type, //文件类型
      tempArray: [], //储存云数据的状态
      downloadCenter:this.props.downloadCenter
    };
  }

  componentWillMount(){
    // this.fetchCloudDatas();
    // console.log("CloudDatas",this.state.allCloudDatas);
    // console.log("data",this.props.data);
    this.fetchData();
  }
  componentDidMount(){

  }

  getNativeWpsDatas(){
    RNFileSearch.getWpsResult();
    DeviceEventEmitter.addListener('WpsArray',(e)=>{

    for(var i=0;i<e.length;i++){
      if(this.state.tempArray[e[i].title]){
        this.state.cloudDatas.push(e[i])
      }else{
        this.state.nativeDatas.push(e[i])
      }
    }
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(this.state.nativeDatas)
    })

    });
  }
  getNativePptDatas(){
    RNFileSearch.getPptResult();
    DeviceEventEmitter.addListener('PptArray',(e)=>{
    for(var i=0;i<e.length;i++){
      if(this.state.tempArray[e[i].title]){
        this.state.cloudDatas.push(e[i])
      }else{
        this.state.nativeDatas.push(e[i])
      }
    }
    this.setState({dataSource: this.state.dataSource.cloneWithRows(this.state.nativeDatas)})
    });
  }
  getNativeAudioDatas(){
    RNFileSearch.getAudioResult();
    DeviceEventEmitter.addListener('AudioArray',(e)=>{
    for(var i=0;i<e.length;i++){
      if(this.state.tempArray[e[i].title]){
        this.state.cloudDatas.push(e[i])
      }else{
        this.state.nativeDatas.push(e[i])
      }
    }
    this.setState({dataSource: this.state.dataSource.cloneWithRows(this.state.nativeDatas)})
    });
  }
  getNativePicDatas(){
    RNFileSearch.getImageResult();
    DeviceEventEmitter.addListener('ImageArray',(e)=>{
    for(var i=0;i<e.length;i++){
      if(this.state.tempArray[e[i].title]){
        this.state.cloudDatas.push(e[i])
      }else{
        this.state.nativeDatas.push(e[i])
      }
    }
    this.setState({dataSource: this.state.dataSource.cloneWithRows(this.state.nativeDatas)})
    })
  }
  getNativeVideoDatas(){
    RNFileSearch.getVideoResult();
    DeviceEventEmitter.addListener('VideoArray',(e)=>{
    for(var i=0;i<e.length;i++){
      if(this.state.tempArray[e[i].title]){
        this.state.cloudDatas.push(e[i])
      }else{
        this.state.nativeDatas.push(e[i])
      }
    }
    this.setState({dataSource: this.state.dataSource.cloneWithRows(this.state.nativeDatas)})
    })
  }
  getNativeLabelDatas(){
    RNFileSearch.getLabelResult();
    DeviceEventEmitter.addListener('LabelArray',(e)=>{
    for(var i=0;i<e.length;i++){
      if(this.state.tempArray[e[i].title]){
        this.state.cloudDatas.push(e[i])
      }else{
        this.state.nativeDatas.push(e[i])
      }
    }
    this.setState({dataSource: this.state.dataSource.cloneWithRows(this.state.nativeDatas)})
    })
  }
  fetchData(){
    for (var i = 0; i < this.state.allCloudDatas.length; i++) {
      this.state.tempArray[this.state.allCloudDatas[i].name] = true;
    }
    (this.state.type=='file' && this.getNativeWpsDatas()
    || this.state.type=='slide' && this.getNativePptDatas()
    || this.state.type=='audio' && this.getNativeAudioDatas()
    || this.state.type=='pic' && this.getNativePicDatas()
    || this.state.type=='video' && this.getNativeVideoDatas()
    || this.state.type=='label' && this.getNativeLabelDatas())
  }

  allSelect(){
    if(this.state.allSelect){
      if(this.state.unuploaded){
        for(var i=0;i<this.state.nativeDatas.length;i++){
          this.state.nativeDatas[i].selected = false;
        }
      }
      else{
        for(var i=0;i<this.state.cloudDatas.length;i++){
          this.state.cloudDatas[i].selected = false;
        }
      }
      this.setState({allSelect:false,titleRight:'全选'});
    }else{
      if(this.state.unuploaded){
        for(var i=0;i<this.state.nativeDatas.length;i++){
          this.state.nativeDatas[i].selected = true;
        }
      }else{
        for(var i=0;i<this.state.cloudDatas.length;i++){
          this.state.cloudDatas[i].selected = true;
        }
      }
      this.setState({allSelect:true,titleRight:'取消'});
    }
  }

  _pressRowForEdit(file,rowID){
    console.log(file);
    if(this.state.unuploaded){
      if(file.selected){
        file.selected = false;
        this.state.checkRows.remove(file);
        this.setState({dataSource: this.state.dataSource.cloneWithRows(this.state.nativeDatas)})
      }else{
        file.selected = true;
        this.state.checkRows.push(file);
        this.setState({dataSource: this.state.dataSource.cloneWithRows(this.state.nativeDatas)})
      }
    }
  }

  _renderRowForEdit(file,sectionID,rowID) {
        console.log(file.filePath);
        var select;
        if(this.state.unuploaded){
          if(file.selected == true){
            select = <View>
                      <Image
                        style={styles.rowIcon}
                        source={require('./img/check.png')} />
                     </View>;
          }else{
            select = <View>
                      <Image
                        style={styles.rowIcon}
                        source={require('./img/unchecked.png')} />
                     </View>
          }
        }



        return (
            <TouchableOpacity onPress={()=>this._pressRowForEdit(file,rowID)}>
              <View style={styles.container}>
                <Image
                  source={{uri:'file://'+file.filePath}}
                  style={styles.thumbnail}
                  ></Image>
                <View style={styles.rightContainer}>
                  <Text style={styles.title} numberOfLines={1}>{file.title}</Text>
                  <Text style={styles.year}>{file.year}</Text>
                </View>
                {
                  select
                }
              </View>
            </TouchableOpacity>
          );
  }

  goback(){
    const { navigator } = this.props;

    if(navigator) {
        this.state.cloudDatas = [];
        this.state.nativeDatas = [];
        navigator.pop();
    }else{
        console.log("路由为空");
    }
  }

  clickFinish(){
    const { navigator } = this.props;
    // console.log('将要上传的列表',this.state.checkRows);
    for (var i = 0; i < this.state.checkRows.length; i++) {
      this.state.checkRows[i].progress = 0;
    }
    // if(this.state.checkRows.length>0){
      this.props.downloadCenter.upload(this.state.checkRows);
    // }
    for (var i = 0; i < this.state.nativeDatas.length; i++) {
      this.state.nativeDatas[i].selected = false;
    }
    this.setState({dataSource:this.state.dataSource.cloneWithRows(this.state.nativeDatas)})

    if(navigator) {
      navigator.push({
        name: 'downloadControl',
        component: DownloadControl,
        params:{
          updata: this.state.checkRows,
          uploadList: true,
          downloadCenter:this.props.downloadCenter
        }
      });
    }
    this.state.checkRows.length = 0
  }

  goUnupload(){
    this.setState({unuploaded:true,titleRight:'全选',dataSource:this.state.dataSource.cloneWithRows(this.state.nativeDatas)});
  }
  goUpload(){
    this.setState({unuploaded:false,titleRight:'',dataSource:this.state.dataSource.cloneWithRows(this.state.cloudDatas)});
  }

  render(){
    var loading;
    if(this.state.nativeDatas.length>0){
      loading= (<View style={{flex:1}}>
      <ListView
        style={{flex:1}}
        dataSource={this.state.dataSource}
        renderRow={this._renderRowForEdit.bind(this)} />
    </View>)
    }else{
      loading=<View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
        <ProgressBarAndroid/>
      </View>
    }
    return (
      <View style={{flex:1}}>
        <View style={styles.head}>
          <TouchableOpacity onPress={this.goback.bind(this)}>
          <View style={{justifyContent:'center',marginLeft:15}}>
            <Image
              style={styles.headBack}
              source={require('./img/back.png')} />
          </View>
          </TouchableOpacity>

          <View style={styles.headTitle}>
            <Text style={{left:105,color:'white',marginTop:15}}>选择文档</Text>
          </View>

          <View style={{justifyContent:'center',}}>
            <TouchableOpacity onPress={this.allSelect.bind(this)}>
             <Text style={{marginLeft:210,textAlign:'center',color:'white'}}>{this.state.titleRight}</Text>
            </TouchableOpacity>
          </View>
        </View>

        <View style={{flexDirection:'row',height:40}}>
          <TouchableOpacity onPress={this.goUnupload.bind(this)}>
            <Image
              style={{width:width/2,height:40}}
              source={require('./img/select/bgl.png')} >
              <View style={{marginLeft:70,marginTop:10}}>
                <Text style={[this.state.unuploaded ? styles.selectedTab:styles.unselectedTab]}>未上传({this.state.nativeDatas.length || 0})</Text>
              </View>
            </Image>
          </TouchableOpacity>
          <TouchableOpacity onPress={this.goUpload.bind(this)}>
            <Image
              style={{width:width/2,height:40}}
              source={require('./img/select/bgr.png')} >
              <View style={{marginTop:10,marginRight:70}}>
                <Text style={[(!this.state.unuploaded) ? styles.selectedTab:styles.unselectedTab]}>已上传({this.state.cloudDatas.length || 0})</Text>
              </View>
            </Image>
          </TouchableOpacity>
        </View>

        {loading}

        <TouchableOpacity onPress={this.clickFinish.bind(this)}>
        <View style={styles.bottomFinish}>
          <Text style={[styles.finish]}>完成</Text>
          <Text style={{width:5}}/>
          <Image
            style={{width:10,height:10}}
            source={require('./img/check.png')} />
        </View>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  head:{
    height:50,
    flexDirection:'row',
    backgroundColor:'#6d9eeb'
  },
  headBack:{
    width:30,
    height:30,
    marginTop:12
  },
  rowIcon:{
    width:10,
    height:10,
    marginTop:30,
    marginRight:20
  },
  container: {
    height: 65,
    flexDirection: 'row',
    backgroundColor:'#FFFFFF'
  },
  rightContainer: {
    flex:1,
    marginLeft:8,
  },
  thumbnail: {
    marginTop:10,
    marginLeft:15,
    width: 40,
    height: 50,
  },
  title:{
    marginBottom: 8,
    marginTop:13,
    marginLeft:15,
    width:240,
    color:'black',
    fontSize:16
  },
  year:{
    fontSize: 12,
    marginTop:-5,
    marginLeft:15,
  },
  finish:{
    color:'#33AA68'
  },
  unselectedTab:{
    textAlign:'center'
  },
  selectedTab:{
    color:'#33AA68',
    textAlign:'center'
  },
  listImg: {
    width:10,
    height:10,
    marginRight:15
  },
  bottomFinish:{
    backgroundColor:'#FFFFFF',
    height:50,
    flexDirection:'row',
    justifyContent:'center',
    alignItems:'center'
  }
});

module.exports = ListComponent;
